package com.tuda.system.service.impl;

import com.tuda.common.core.text.Convert;
import com.tuda.common.enums.OrderType;
import com.tuda.common.utils.DateUtils;
import com.tuda.common.utils.ToolUtil;
import com.tuda.system.domain.TudaAppletUser;
import com.tuda.system.domain.TudaOrder;
import com.tuda.system.domain.TudaOrderTransfer;
import com.tuda.system.mapper.TudaAppletUserMapper;
import com.tuda.system.mapper.TudaOrderMapper;
import com.tuda.system.mapper.TudaOrderTransferMapper;
import com.tuda.system.model.result.OrderTotalAmountResult;
import com.tuda.system.service.ITuDaFinanceService;
import com.tuda.system.service.ITudaOrderRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName TuDaFinanceServiceImpl
 * @Description TODO
 * @Author Admin
 * @Date 2023/7/31 11:55
 * @Version 1.0
 **/
@Service
public class TuDaFinanceServiceImpl implements ITuDaFinanceService {

    @Resource
    private TudaOrderMapper tudaOrderMapper;
    @Resource
    private TudaOrderTransferMapper orderTransferMapper;
    @Resource
    private TudaAppletUserMapper appletUserMapper;
    @Resource
    private ITudaOrderRecordService orderRecordService;
    @Resource
    private TudaOrderServiceImpl orderService;

    @Override
    public List<TudaOrderTransfer> detailed(String ids) {

        List<TudaOrderTransfer> orderTransfers = new ArrayList<>();

        String[] tIds = Convert.toStrArray(ids);
        for (int i = 0; i < tIds.length; i++) {
            TudaOrderTransfer orderTransfer = orderTransferMapper.queryTInfoById(Long.valueOf(tIds[i]));
            if(ToolUtil.isNotEmpty(orderTransfer) && !orderTransfer.getRefund()){
                TudaOrder order = tudaOrderMapper.selectTudaOrderById(orderTransfer.getOrderId());
                if(ToolUtil.isNotEmpty(order)){
                    orderTransfer.setVehicleModel(order.getVehicleModel());
                    orderTransfer.setOrigin(order.getOrigin());
                    orderTransfer.setDest(order.getDest());
                }
                orderTransfers.add(orderTransfer);
            }
        }
        return orderTransfers;
    }

    @Override
    public List<TudaOrderTransfer> detailedInfoByHeadPhone(String headPhone, String orderId) {
        List<TudaOrderTransfer> list = orderTransferMapper.detailedInfoByHeadPhone(headPhone, Long.valueOf(orderId));
        for (TudaOrderTransfer orderTransfer : list){
            TudaOrder order = tudaOrderMapper.selectTudaOrderById(orderTransfer.getOrderId());
            if(ToolUtil.isNotEmpty(order)){
                orderTransfer.setVehicleModel(order.getVehicleModel());
                orderTransfer.setOrigin(order.getOrigin());
                orderTransfer.setDest(order.getDest());
            }
        }
        return list;
    }

    /**
     * 查询货运订单
     *
     * @param id 货运订单主键
     * @return 货运订单
     */
    @Override
    public TudaOrder selectTudaOrderById(Long id)
    {
        return tudaOrderMapper.selectTudaOrderById(id);
    }

    /**
     * 查询货运订单列表
     *
     * @param tudaOrder 货运订单
     * @return 货运订单
     */
    @Override
    public List<TudaOrder> selectTudaOrderList(TudaOrder tudaOrder) {
        if(ToolUtil.isNotEmpty(tudaOrder.getTransporter())){
            tudaOrder.setType(1);
        }
        List<TudaOrder> orderList = tudaOrderMapper.queryTudaOrderList(tudaOrder);
        for(TudaOrder order : orderList){
            order.setOrderId(order.getId());
            order.setNotGive(orderTransferMapper.selectOrderTCount2(order.getId()) > 0 ? true : false);
            order.setNotPay(orderTransferMapper.selectOrderTCount1(order.getId()) > 0 ? true : false);
            TudaAppletUser appletUser= appletUserMapper.selectTudaAppletUserById(order.getUserId());
            if(ToolUtil.isNotEmpty(appletUser)){
                order.setCreateUser(appletUser.getNickName());
            }
        }
        return orderList;
    }

    @Override
    public OrderTotalAmountResult selectTotalAmount(TudaOrder tudaOrder) {
        if(ToolUtil.isNotEmpty(tudaOrder.getTransitBranch()) || (ToolUtil.isNotEmpty(tudaOrder.getRefund()) && tudaOrder.getRefund() > 0)){
            tudaOrder.setType(1);
        }
        OrderTotalAmountResult totalAmountResult = tudaOrderMapper.selectTotalAmount(tudaOrder);
        return totalAmountResult;
    }

    /**
     * 修改货运订单
     *
     * @param tudaOrder 货运订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTudaOrder(TudaOrder tudaOrder)
    {
        tudaOrder.setUpdateTime(DateUtils.getNowDate());
        tudaOrder.setOrderType(OrderType.ORDER_4.getCode());
        tudaOrderMapper.deleteTudaOrderTransferByOrderId(tudaOrder.getId());
        if(ToolUtil.isNotEmpty(tudaOrder.getUserName())){
            String[] str = tudaOrder.getUserName().split(",");
            if(str.length > 1){
                tudaOrder.setUserName(str[0]);
                tudaOrder.setSalesmanPhone(str[1]);
            }
        }

        return tudaOrderMapper.updateTudaOrder(tudaOrder);
    }

    /**
     * 批量删除货运订单
     *
     * @param ids 需要删除的货运订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int settlement(String ids)
    {
        String[] tId = Convert.toStrArray(ids);
        for (int i = 0; i < tId.length; i++) {
            int count = orderTransferMapper.updateRefund(Long.valueOf(tId[i]));
            if(count > 0){
                TudaOrderTransfer orderTransfer = tudaOrderMapper.queryInfoById(Long.valueOf(tId[i]));
                if(ToolUtil.isNotEmpty(orderTransfer)){
                    if(orderTransfer.getOwes().compareTo(new BigDecimal(0.00)) == 1){
                        orderRecordService.insertOrderRecord(orderTransfer.getOrderId(), "中转欠返结算", orderTransfer.getOwes(),null,null);
                    }
                    if(orderTransfer.getOwes().compareTo(new BigDecimal(0.00)) < 0){
                        orderRecordService.insertOrderRecord(orderTransfer.getOrderId(), null, null,"中转欠付结算",orderTransfer.getOwes());
                    }
                    int num = orderTransferMapper.selectCount(orderTransfer.getOrderId());
                    System.out.println(orderTransfer.getOrderId()+"---------------------------"+num);
                    if(num <= 0){
                        tudaOrderMapper.updateOrderType(orderTransfer.getOrderId(), OrderType.ORDER_6.getCode());
                    }
                }
            }
        }
        return 1;
    }

    @Override
    public int salesman(String ids) {
        {
            int a = 0;
            String[] tId = Convert.toStrArray(ids);
            for (int i = 0; i < tId.length; i++) {
                orderTransferMapper.updateRefund(Long.valueOf(tId[i]));
                TudaOrderTransfer orderTransfer = tudaOrderMapper.queryInfoById(Long.valueOf(tId[i]));
                if(ToolUtil.isNotEmpty(orderTransfer)){
                    int num = orderTransferMapper.selectCount(orderTransfer.getOrderId());
                    if(num == 0){
                        tudaOrderMapper.updateOrderType(orderTransfer.getOrderId(), OrderType.ORDER_6.getCode());
                    }
                }
                a++;
            }
            return a;
        }
    }

    @Override
    public List<TudaOrder> salesmanList(String ids) {
        List<TudaOrder> orderList = new ArrayList<>();
        String[] orderIds = Convert.toStrArray(ids);
        for (int i = 0; i < orderIds.length; i++) {
           TudaOrder order = tudaOrderMapper.selectTudaOrderById(Long.valueOf(orderIds[i]));
           if(ToolUtil.isNotEmpty(order)){
               orderList.add(order);
           }
            TudaAppletUser appletUser= appletUserMapper.selectTudaAppletUserById(order.getUserId());
            if(ToolUtil.isNotEmpty(appletUser)){
                order.setCreateUser(appletUser.getNickName());
            }
        }
        return orderList;
    }

    public List<TudaOrderTransfer> salesmanTransferList(String ids) {
        List<TudaOrderTransfer> list = tudaOrderMapper.salesmanList(Convert.toStrArray(ids));
        for (TudaOrderTransfer orderTransfer : list){
            TudaOrder order = tudaOrderMapper.selectTudaOrderById(orderTransfer.getOrderId());
            if(ToolUtil.isNotEmpty(order)){
                orderTransfer.setVehicleModel(order.getVehicleModel());
                orderTransfer.setOrigin(order.getOrigin());
                orderTransfer.setDest(order.getDest());
            }
        }
        return list;
    }

    @Override
    public List<TudaOrder> queryCompanyOrderListByPhone(TudaOrder tudaOrder) {
        tudaOrder.setType(1);
        List<TudaOrder> orderList = tudaOrderMapper.queryCompanyOrderListByPhone(tudaOrder);
        for(TudaOrder order : orderList){
//            if(ToolUtil.isNotEmpty(tudaOrder.getTransporter()) || ToolUtil.isNotEmpty(tudaOrder.getTransporterPhone()) || ToolUtil.isNotEmpty(tudaOrder.getPlateNumber())){
//                TudaOrderTransfer tudaOrderTransfer = tudaOrderMapper.queryInfoByValue(order.getId(), tudaOrder.getTransporter(), tudaOrder.getTransporterPhone(), tudaOrder.getPlateNumber());
//                if(ToolUtil.isNotEmpty(tudaOrderTransfer)){
//                    order.setOrderId(order.getId());
//                    order.setId(tudaOrderTransfer.getId());
//                    order.setOrderTransferId(tudaOrderTransfer.getId());
//                    order.setTransporter(tudaOrderTransfer.getTransporter());
//                    order.setTransporterPhone(tudaOrderTransfer.getTransporterPhone());
//                    order.setOwes(tudaOrderTransfer.getOwes());
//                    order.setPlateNumber(tudaOrderTransfer.getPlateNumber());
//                    order.setAmount(tudaOrderTransfer.getAmount());
//                    order.setTransferFee(tudaOrderTransfer.getTransferFee());
//                    order.setRefund(tudaOrderTransfer.getRefund() ? 1 : 0);
//                }
//            }else {
            order.setHeadPhone(tudaOrder.getHeadPhone());
            order.setNotGive(orderTransferMapper.selectOrderTCount2(order.getId()) > 0 ? true : false);
            order.setNotPay(orderTransferMapper.selectOrderTCount1(order.getId()) > 0 ? true : false);
//                if(order.getProfit().compareTo(new BigDecimal(0)) == 0){
            List<TudaOrderTransfer> transferList = orderTransferMapper.queryByInfo(order.getId());
            // 总运费 + 已收费用 = 总收
            BigDecimal amount = order.getFreightAmount().add(order.getPaidAmount());
            // 总收 - 中转费 - （各种费用） = 得到基本费用
            amount = amount.subtract(order.getDrivingFee()).subtract(order.getForkliftFee()).subtract(order.getInspectionFee()).
                    subtract(order.getRefuelingFee()).subtract(order.getSmallBoardFee()).subtract(order.getAgencyFee()).subtract(order.getOtherFee());
            if(transferList.size() > 0){
                for(TudaOrderTransfer orderTransfer : transferList){
                    // 基本费用 - 司机运费 = 利润
                    amount = amount.subtract(orderTransfer.getTransferFee());
                }
                // 利润(没有减掉业务员提成)
                order.setProfit(amount);
                TudaAppletUser user = appletUserMapper.selectTudaAppletUserByPhone(ToolUtil.isNotEmpty(order.getSalesmanPhone()) ? order.getSalesmanPhone() : null);
                if(ToolUtil.isNotEmpty(user)){
                    // 业务员提成（金额+已付金额-中介费-提验费-代驾费-加油费-小板费-叉车费-其他费-所有中转费）*业务员提成百分比
                    order.setCommission(amount.multiply((user.getPercentage().divide(new BigDecimal(100)))));
                    // 利润（减掉业务员提成）
                    order.setProfit(order.getProfit().subtract(order.getCommission()));
                }
            }
            tudaOrderMapper.updateOrderInfo(order.getId(), order.getProfit(), order.getCommission());
            TudaAppletUser appletUser= appletUserMapper.selectTudaAppletUserById(order.getUserId());
            if(ToolUtil.isNotEmpty(appletUser)){
                order.setCreateUser(appletUser.getNickName());
            }
        }
        return orderList;
    }

    @Override
    public int updateOrderFee(Long orderId, String feeState, String feeName, String notes, BigDecimal amount, String feeAmount) {
        int num = tudaOrderMapper.updateOrderFee(orderId, feeState, feeName, notes, amount, feeAmount);
        if(num > 0){
//            orderService.statistics(orderId);
            orderRecordService.insertOrderRecord(orderId, null, null,"杂费结算", amount.negate());
        }
        return 1;
    }

    @Transactional
    @Override
    public int refund(String id) {
        int count = orderTransferMapper.updateRefund(Long.valueOf(id));
        if(count > 0){
            TudaOrderTransfer orderTransfer = tudaOrderMapper.queryInfoById(Long.valueOf(id));
            if(ToolUtil.isNotEmpty(orderTransfer)){
                if(orderTransfer.getOwes().compareTo(new BigDecimal(0.00)) == 1){
                    orderRecordService.insertOrderRecord(orderTransfer.getOrderId(), "中转欠返结算", orderTransfer.getOwes(),null,null);
                }
                if(orderTransfer.getOwes().compareTo(new BigDecimal(0.00)) < 0){
                    orderRecordService.insertOrderRecord(orderTransfer.getOrderId(), null, null,"中转欠付结算",orderTransfer.getOwes());
                }
            }
        }
        return 1;
    }

    @Override
    public int orderCompletion(String id) {
       TudaOrder order = tudaOrderMapper.selectTudaOrderById(Long.valueOf(id));
       if(ToolUtil.isNotEmpty(order)){
           if(order.getPayType() == 3){
               order.setPayType(1L);
           }
           order.setOrderType(OrderType.ORDER_6.getCode());
           return tudaOrderMapper.updateTudaOrder(order);
       }
        return 0;
    }

}
